package com.ilxqx.generator.key.impl;

import com.ilxqx.generator.enumeration.ConstraintKeyEnum;
import com.ilxqx.generator.key.ConstraintKey;
import com.ilxqx.generator.parser.TableField;
import lombok.Setter;

import java.util.Comparator;
import java.util.List;

/**
 * 限制键实现类
 * @author venus
 */
@Setter
public class ConstraintKeyImpl implements ConstraintKey {

    private String keyName;

    private ConstraintKeyEnum keyType;

    private List<ConstraintKey.KeyMember> keyMembers;

    public ConstraintKeyImpl() {
    }

    public ConstraintKeyImpl(String keyName, ConstraintKeyEnum keyType) {
        this.keyName = keyName;
        this.keyType = keyType;
    }

    /**
     * 获取键的名称
     *
     * @return 键名称
     */
    @Override
    public String getKeyName() {
        return this.keyName;
    }

    /**
     * 判断是否是复合键
     *
     * @return bool
     */
    @Override
    public boolean isComposite() {
        return this.keyMembers.size() > 1;
    }

    /**
     * 返回键的类型
     *
     * @return 键类型
     */
    @Override
    public ConstraintKeyEnum getKeyType() {
        return this.keyType;
    }

    /**
     * 获取参与键构成的第一个字段
     *
     * @return 表字段对象
     */
    @Override
    public KeyMember getFirstFieldMember() {
        return this.keyMembers.get(0);
    }

    /**
     * 获取该键的所有构成字段
     *
     * @return 表字段List
     */
    @Override
    public List<KeyMember> getFields() {
        return this.keyMembers;
    }

    public void setKeyMembers(List<KeyMember> keyMembers) {
        // 做个自然排序根据seq
        keyMembers.sort(Comparator.comparingInt(KeyMember::getSeq));
        this.keyMembers = keyMembers;
    }

    public static class KeyMemberImpl implements KeyMember {

        /**
         * 表字段对象
         */
        private TableField tableField;

        /**
         * 键索引
         */
        private int seq;

        public KeyMemberImpl(TableField tableField, int seq) {
            this.tableField = tableField;
            this.seq = seq;
        }

        /**
         * 获取表字段
         *
         * @return 表字段对象
         */
        @Override
        public TableField getField() {
            return this.tableField;
        }

        /**
         * 获取该字段在键中的索引（序号）
         *
         * @return 索引
         */
        @Override
        public int getSeq() {
            return this.seq;
        }

    }

}
